﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Models;
using System.Data;
using System.Data.SqlClient;

namespace DAL
{
    public class LoginUserDal
    {
        DbManager db = new DbManager();

        /// <summary>
        /// 根据dataReader获取单挑数据
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        private LoginUserModel GetSingleDataByDataReader(SqlDataReader reader)
        {
            LoginUserModel lum = new LoginUserModel();
            while (reader.Read())
            {
                lum.User_id = reader["User_id"].ToString();
                lum.AotuId = int.Parse(reader["AotuId"].ToString());
                lum.CreateTime = DateTime.Parse(reader["CreateTime"].ToString());
                lum.UpdateTime = DateTime.Parse(reader["UpdateTime"].ToString());
                lum.UserAccount = reader["UserAccount"].ToString();
                lum.UserPwd = reader["UserPwd"].ToString();
                lum.DepartId = reader["DepartId"].ToString();
                lum.DepartName = reader["DepartName"].ToString();
                lum.IsManager = bool.Parse(reader["IsManager"].ToString())?'1':'0';
                lum.OpenId = reader["OpenId"].ToString();
                lum.NickName = reader["NickName"].ToString();
                lum.Phone = reader["Phone"].ToString();
            }
            reader.Close();
            reader.Dispose();
            return lum;
        }

        /// <summary>
        /// 根据dataReader获取所有数据
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        private List<LoginUserModel> GetDataListByDataReader(SqlDataReader reader)
        {
            List<LoginUserModel> lumLi = new List<LoginUserModel>();
            while (reader.Read())
            {
                LoginUserModel lum = new LoginUserModel();
                lum.User_id = reader["User_id"].ToString();
                lum.AotuId = int.Parse(reader["AotuId"].ToString());
                lum.CreateTime = DateTime.Parse(reader["CreateTime"].ToString());
                lum.UpdateTime = DateTime.Parse(reader["UpdateTime"].ToString());
                lum.UserAccount = reader["UserAccount"].ToString();
                lum.UserPwd = reader["UserPwd"].ToString();
                lum.DepartId = reader["DepartId"].ToString();
                lum.DepartName = reader["DepartName"].ToString();
                lum.IsManager = bool.Parse(reader["IsManager"].ToString()) ? '1' : '0';
                lum.OpenId = reader["OpenId"].ToString();
                lum.NickName = reader["NickName"].ToString();
                lum.Phone = reader["Phone"].ToString();
                lum.AddUserId = reader["AddUserId"].ToString();
                lumLi.Add(lum);
            }
            reader.Close();
            reader.Dispose();
            return lumLi;
        }

        public List<LoginUserModel> GetDataList()
        {
            string sql = "select User_id,AotuId,CreateTime,UpdateTime,UserAccount,UserPwd,DepartId,IsManager,OpenId, (select UnitName from Unit where UnitId=DepartId) as DepartName,Phone,NickName,AddUserId from  LoginUser";
            SqlDataReader reader = db.RunDataReaderResultSql(sql);
            return GetDataListByDataReader(reader);
        }

        /// <summary>
        /// 创建单个用户
        /// </summary>
        /// <returns></returns>
        public bool InsertSingleData(LoginUserModel lum)
        {
            string sql = "insert LoginUser(CreateTime,UpdateTime,UserAccount,UserPwd,isManager,openid) values(GETDATE(),GETDATE(),'" + lum.UserAccount + "','" + lum.UserPwd + "',0,'" + lum.OpenId + "')";
            try
            {
                db.RunNoneResultSql(sql);
                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }

         //<summary>
         //根据code码修改单位信息
         //</summary>
         //<param name = "code" ></ param >
         //< returns ></ returns >
        public string[] SetManageByCode(string UnitCode, string userId)
        {
            string[] strArr = new string[3];
            UnitModel unit =  new Unit.UnitDAL().GetEntityBySeqCode(UnitCode);
            if (unit == null || string.IsNullOrEmpty(unit.UnitId))
            {
                strArr[0] = "-2";
                return strArr;
            }
            else
            {
                string sql = "update LoginUser set IsManager=0,DepartId='"+unit.UnitId+"',DepartName='"+unit.UnitName+"' where User_id='" + userId + "'";
                try
                {
                    db.RunNoneResultSql(sql);
                    strArr[0] = "0";
                    strArr[1] = unit.UnitId;
                    strArr[2] = unit.UnitName;
                    return strArr;
                }
                catch (Exception ex)
                {
                    strArr[0] = "-1";
                    return strArr;
                }
            }
           
          
        }


        /// <summary>
        /// 根据userId获取单挑数据
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public LoginUserModel GetSingleDataByUserId(string userId)
        {
            string sql = "select * from LoginUser where cast(User_id as varchar(36))='" + userId + "'";
            SqlDataReader readder = db.RunDataReaderResultSql(sql);
            return GetSingleDataByDataReader(readder);
        }


        /// <summary>
        /// 根据userid或者openId获取单条数据
        /// </summary>
        /// <param name="userNo"></param>
        /// <returns></returns>
        public LoginUserModel GetSingleDataByUserNo(string userNo)
        {
            string sql = "select * from LoginUser where cast(User_id as varchar(36))='" + userNo + "' or OpenId='"+userNo+"'";
            SqlDataReader readder = db.RunDataReaderResultSql(sql);
            return GetSingleDataByDataReader(readder);
        }
        /// <summary>
        /// 根据userid判断是不是本人完善自己信息，是本人需要补充本人人员信息
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="departId"></param>
        /// <param name="departName"></param>
        /// <param name="addUserName"></param>
        /// <param name="isManger">1是管理员，0不是</param>
        /// <returns></returns>
        public bool UpdateUserInfo(string userId, string departId, string departName, string addUserId,int isManger=0)
        {
            string sql = "select count(1) from LoginUser where cast(User_id as varchar(36))='" + userId + "'";
            object o = db.GetFirstData(sql);
            if (int.Parse(o.ToString()) > 0)
            {
                sql = "update LoginUser set DepartId='" + departId + "',DepartName='" + departName + "',IsManager='"+ isManger + "',AddUserId='" + addUserId + "' where User_id='" + userId + "'";
                try
                {
                    db.RunNoneResultSql(sql);
                    return true;
                }
                catch (Exception ex)
                {

                    return false;
                }

            }
            else//不是本人给本人完善信息不操作
            {
                return true;
            }
        }

        /// <summary>
        /// 根据userAccount获取单挑数据
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public LoginUserModel GetSingleDataByUserAccount(string userAccount)
        {
            string sql = "select * from LoginUser where UserAccount='" + userAccount + "'";
            SqlDataReader readder = db.RunDataReaderResultSql(sql);
            return GetSingleDataByDataReader(readder);
        }

        /// <summary>
        /// 根据userid或者Openid或者用户账号获取当前用户是否是管理员
        /// </summary>
        /// <param name="userNo"></param>
        /// <returns></returns>
        public bool IsManager(string userNo)
        {
            string sql = "select IsManager from LoginUser where cast(User_id as varchar(36))='" + userNo+ "' or OpenId='" + userNo + "' or UserAccount='" + userNo + "'";
            object o = db.GetFirstData(sql);
            if (o == null)
            {
                return false;
            }
            else
            {
                return bool.Parse(o.ToString());
            }
        }

   
        /// <summary>
        /// 将单位信息关联到账户表，并将第一个关联的用户设置为管理员
        /// </summary>
        /// <param name="departId"></param>
        /// <param name="departName"></param>
        /// <param name="userID"></param>
        /// <returns></returns>
        public bool UpdateDepartInfo(string departId, string departName, string userID)
        {
            
            LoginUserModel lum = new LoginUserDal().GetSingleDataByUserId(userID);
            if (string.IsNullOrEmpty(lum.DepartId))//表示此用户是第一次做单位添加，默认为管理员（一个用户只能有一个单位）
            {
                return UpdateSingleData(departId, departName, userID, 1);
            }
            else//如果有第二次不允许更改第一次的单位信息
            {
                //return UpdateSingleData(departId, departName, userID, 0);
                return true;
            }
        }


        /// <summary>
        /// 根据OpenId获取单挑数据
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public LoginUserModel GetSingleDataByOpenId(string openId)
        {
            string sql = "select User_id,AotuId,CreateTime,UpdateTime,UserAccount,UserPwd,DepartId,IsManager,OpenId, (select UnitName from Unit where UnitId=DepartId) as DepartName,NickName,phone from LoginUser where OpenId='" + openId + "'";
            SqlDataReader readder = db.RunDataReaderResultSql(sql);
            return GetSingleDataByDataReader(readder);
        }

        /// <summary>
        /// 根据用户id填写单位id和单位名称和管理员状态
        /// </summary>
        /// <param name="departId"></param>
        /// <param name="departName"></param>
        /// <param name="userID"></param>
        /// <returns></returns>
        public bool UpdateSingleData(string departId, string departName, string userID, int isNameger)
        {
            string sql = "update LoginUser set departId='" + departId + "',departName='" + departName + "',IsManager='" + isNameger + "' where User_id='" + userID + "'";
            try
            {
                db.RunNoneResultSql(sql);
                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }


        /// <summary>
        /// 根据departName获取查询到的数据的数量
        /// </summary>
        /// <param name="departName"></param>
        /// <returns></returns>
        public int GetCountByDepartName(string departName)
        {
            string sql = "select count(1) from LoginUser where departName='" + departName + "'";
            object o = db.GetFirstData(sql);
            return int.Parse(o.ToString());
        }

        /// <summary>
        /// 根据id获取人员信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public EmployeeModel GetEmployeeById(string  id)
        {
            string sql = "select  DisplayName,Age,EmployeeId,Post,Gender from Employee where cast(EmployeeId as varchar(36))='" + id+"'";
            EmployeeModel elm = new EmployeeModel();
            SqlDataReader raeder = db.RunDataReaderResultSql(sql);
            while (raeder.Read())
            {
                elm.DisplayName = raeder["DisplayName"].ToString();
                elm.Age = int.Parse(raeder["Age"].ToString());
                elm.Post= raeder["Post"].ToString();
                elm.Gender = raeder["Gender"].ToString();
            }
            raeder.Close();
            raeder.Dispose();

            return elm;
        }

        /// <summary>
        /// 根据id删除单挑数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DelSingleDataById(string id)
        {
            string sql = "delete LoginUser where User_id='"+id+"'";
            try
            {
                db.RunNoneResultSql(sql);
                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }

        /// <summary>
        /// 根据人员id获取图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AttachmentModel GetAttachmentById(string parentId)
        {
            string sql = "select * from Attachment where BusinessId='"+ parentId + "' and [Option]='photo'";
            SqlDataReader reader = db.RunDataReaderResultSql(sql);
            AttachmentModel am = new AttachmentModel();
            while (reader.Read())
            {
                am.AttachmentId = Guid.Parse(reader["AttachmentId"].ToString());
                am.FileName = reader["FileName"].ToString();
                am.Extension = reader["Extension"].ToString();
                am.MediaType = reader["MediaType"].ToString();
                am.FileName = reader["FileName"].ToString();
            }
            reader.Close();
            reader.Dispose();
            return am;
        }


        /// <summary>
        /// 根据departId判断是否存在单位信息
        /// </summary>
        /// <param name="departId"></param>
        /// <returns></returns>
        public int SetDeaprt(string departId,string userId)
        {
            string sql = "select COUNT(1) from Unit where UnitId='"+departId+"'";
            int count = int.Parse(db.GetFirstData(sql).ToString());
            if (count == 0)
            {
                sql = "update LoginUser set DepartId='',DepartName='' from LoginUser where User_id='"+ userId + "'";
                try
                {
                    db.RunNoneResultSql(sql);
                    return 0;
                }
                catch (Exception ex)
                {

                    return -1;
                }
            }
            else
            {
                return 1;//单位存在直接返回
            }
        }

        /// <summary>
        /// 根据userId修改昵称
        /// </summary>
        /// <param name="nickName"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool UpdateNickName(string nickName,string userId)
        {
            string sql = "update LoginUser set NickName='"+nickName+"' where User_id='"+userId+"'";
            try
            {
                db.RunNoneResultSql(sql);
                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }

        /// <summary>
        /// 根据userId修改是否为管理员（0不是管理员，1是管理员）
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="isManager"></param>
        /// <returns></returns>
        public bool UpdateManager(string userId,string isManager)
        {
            string sql = "update LoginUser set IsManager='"+isManager+"' where User_id='"+userId+"'";
            try
            {
                db.RunNoneResultSql(sql);
                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }
    }
}
